<template>
  <div id="login">
    <div class="bg">  
    </div>
    <div class="loginBox">
      <div class="title"><h1>实验室管理系统</h1></div>
      <div class="option">
        <span :class="{active:isActive=='login'}"
          @click="isActive='login'"><h2>账号登录</h2></span>
        <span :class="{active:isActive=='register'}"
          @click="isActive='register'"><h2>用户注册</h2></span>
      </div>
      <!-- 登录表单 -->
      <div class="userLogin" :class="{noShow:isActive!=='login'}">
        <Form :model="loginData" :rules="loginRule" ref="loginForm">
            <FormItem prop="username" label="用户名">
                <Input type="text" v-model="loginData.username" placeholder="Username">
                    <Icon type="ios-person-outline" slot="prepend"></Icon>
                </Input>
            </FormItem>
            <FormItem prop="password" label="密码">
                <Input type="password" v-model="loginData.password" placeholder="Password">
                    <Icon type="ios-lock-outline" slot="prepend"></Icon>
                </Input>
            </FormItem>
            <FormItem>
                <Button type="primary" @click="handleSubmitLogin">登录</Button>
            </FormItem>
        </Form>
      </div>
      <!-- 注册表单 -->
      <div class="userRegister" :class="{noShow:isActive!=='register'}">
        <Form :model="registerData"  :rules="registerRule" ref="registerForm">
            <FormItem prop="username" label="用户名">
                <Input type="text" v-model="registerData.username" name="username"></Input>
            </FormItem>
            <FormItem prop="password" label="密码" >
                <Input v-model="registerData.password" name="password" type="password"></Input>
            </FormItem>
            <FormItem prop="nickName" label="用户昵称">
                <Input v-model="registerData.nickName"></Input>
            </FormItem>
            <FormItem prop="phone" label="手机号">
                <Input v-model="registerData.phone"></Input>
            </FormItem>
            <FormItem prop="email" label="邮箱">
                <Input v-model="registerData.email"></Input>
            </FormItem>
            <FormItem>
                <Button type="primary" @click="handleSubmitRegister">注册</Button>
            </FormItem>
        </Form>
      </div>
    </div>
  </div>
</template>

<script>
import qs from 'qs'
//引入验证库
export default {
  data(){
    return{
      isActive:"login",//暴击当前是注册还是登录
      loginData: {
        username: '',
        password: ''
      },
      // 登录信息
      loginRule: {
        username: [
          { required: true, message: 'Please fill in the user name', trigger: 'blur' }
        ],
        password: [
          { required: true, message: 'Please fill in the password.', trigger: 'blur' },
          { type: 'string', min: 6, message: 'The password length cannot be less than 6 bits', trigger: 'blur' }
        ]
      },
      //注册信息
      registerData:{
        username:'',
        password:'',
        nickName:'',
        phone:'',
        email:''
      },
      registerRule:{
        username:[
          { required: true, message: 'Please fill in the user name', trigger: 'blur' }
        ],
        password:[
          { required: true, message: 'Please fill in the user name', trigger: 'blur' },
          { type: 'string', min: 6, message: 'The password length cannot be less than 6 bits', trigger: 'blur' }
        ],
        nickName:[
          { required: true, message: 'Please fill in the user name', trigger: 'blur' }
        ],
        phone:[
          { required: true, message: 'Please fill in the user name', trigger: 'blur' },
          {
              validator: (rule, value, callback)=>{
                // myphone为你要验证的邮箱
                function checkPhone(myphone) {　　
                    var myReg = /^1(3|4|5|6|7|8|9)\d{9}$/;
                    if (myReg.test(myphone)) {　　　　
                        return true;　　
                    } else {　　　　
                        return false;
                    }
                }
                  if(checkPhone(value)){
                      callback()
                  }else{
                      callback(new Error('手机号码格式不正确'))
                  }                  
              }, trigger: 'blur'
          }
        ],
        email:[
          { required: true, message: 'Please fill in the user name', trigger: 'blur' },
          {
              validator: (rule, value, callback)=>{
                // myemail为你要验证的邮箱
                function checkEmail(myemail) {　　
                    var myReg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
                    if (myReg.test(myemail)) {　　　　
                        return true;　　
                    } else {　　　　
                        return false;
                    }
                }
                if(checkEmail(value)){
                    callback()
                }else{
                    callback(new Error('邮箱格式不正确'))
                }                  
              }, trigger: 'blur'
          }
        ]
      }
    }
  },
  methods:{
    //登录
    handleSubmitLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          const {data:res} = await this.$axios.post('/user/login',qs.stringify(this.loginData))
          console.log(res)
          if(res.status !== 200){
            this.$Message.info(res.msg);
            return
          }
          window.sessionStorage.setItem('token',res.token)
          this.$Message.info('登陆成功');
          //将数据存储到vuex
          this.$store.dispatch('setAuthorities',res.authorities)
          
          //存储用户权限
          for(let i = 0; i < res.authorities.length; i++){
            res.authorities[i] = JSON.stringify(res.authorities[i])
          }
          window.sessionStorage.setItem('authorities',JSON.stringify(res.authorities))

          //存储用户名
          window.sessionStorage.setItem('username',this.loginData.username)
          window.sessionStorage.setItem('password',this.loginData.password)
          //存储用户id
          window.sessionStorage.setItem('usermsg',JSON.stringify(res.user))
          this.$router.push({name:'Admin'})
        }
      })
    },
    // 注册
    handleSubmitRegister(){
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          //注册信息,并跳转到相应的页面
          this.registerData.status = true
          const {data:res} = await this.$axios.post('/user/register',this.registerData)
          if(res.status == 200){
            this.$Message.info('注册成功');
            this.isActive = 'login'
            this.registerData.username = ''
            this.registerData.password = ''
            this.registerData.nickName = ''
            this.registerData.phone = ''
            this.registerData.email = ''
          }else{
            this.$Message.info(res.msg);
          }
        }
      })
    }
  }
}
</script>

<style scoped>
  #login{
    height:100%;
    width:100%;
    box-sizing: border-box;
    color:#333;
    overflow:hidden;
  }
/* 内部盒子高=外部盒子高,内部盒子宽>外部盒子宽   */
  .bg{
    width:120%;
    height:100%;
    background:url('../assets/imgs/background.jpg');
    background-size: 100% 100%; /*图片铺满整个内部盒子*/
    background-position: center center; /*图片居中放置*/
    animation: bg 20s infinite linear alternate; /*单次动画20s,无限次,线性播放,左右往返*/
  }
  @keyframes bg {
    from{
        transform:translateX(-10%) /*起始位置*/
    }  
    to{
        transform:translateX(0%) /*结束为止*/
    }
  }
  /* 响应式 */
  /* pc样式 */
  @media screen and (min-width:960px){ 
    #login{
      /* padding-top:6vh */
    }
    .loginBox{
      width:40vw;
      height:500px;
      margin:0 auto;
    }
  } 
  /* pad样式  */
  @media screen and (max-width:960px) and (min-width:750px){ 
    #login{
      /* padding-top:6vh */
    }
    .loginBox{
      width:90vw;
      margin:0 auto;
      height:500px;
    }
  }   
  /* 手机端样式 */
  @media screen and (max-width:750px){ 
    #login{
      /* padding-top:3vh */
    }
    .loginBox{
      width:100%;
      height:500px;
    }
  } 
  .loginBox{
    text-align:center;
    position:fixed;
    left: 50%;
    top: 35%;
    transform:translate(-50%, -50%)
  }
  .title{
    height:50px;
    line-height:50px;
    font-size:1rem;
    margin-bottom:5vh;
  }
  .option{
    height:30px;
    width:100%;
    display: flex;
    margin-bottom:40px;
  }
  .option span{
    flex:1;
    line-height:30px;
    cursor:pointer;
  }
  span.active{
    border-bottom:3px solid #333
  }
  /* 表单 */
  .noShow{
    display:none;
  }
  .ivu-form{
    display:flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
  }
  .ivu-form-item{
    width:60%;
  }
</style>